
package com.ibm.spatiotemp.utils;

import java.sql.*;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.server.datamodel.gpsdata.TSPoint;

/**
 * Insert device config into database
 *
 */
public class TSPointToDB {	
	public final static Logger logger = Logger.getLogger(TSPointToDB.class);
	/**
	 * Reference of DatabaseManager.
	 */
	private Connection conn;
	/**
	 * The buffer size for batch-insert.
	 */
	private int bufferSize = 2000;
	/**
	 * The index in batch-insert.
	 */
	private int index = 0;
	/**
	 * Reference of PreparedStatement for batch-insert.
	 */
	private PreparedStatement ps = null;
	/**
	 * The sql string
	 */
	private String sqlString = null;
	
	
	public TSPointToDB(Connection conn, String sqlString, int size) throws SQLException {
		super();
		this.conn = conn;
		this.sqlString = sqlString;
		this.ps = this.conn.prepareStatement(sqlString);
		this.bufferSize = size;
		this.index = 0;
	}
	
	/*
	 * Add device info into DB
	 */
	public void addPoint(TSPoint tsPoint) throws SQLException  {				
		if (tsPoint.time_stamp == 0) {
			if (index > 0) {
				ps.executeBatch();
				index = 0;
				logger.info("flush by timestamp=0");
			}
			return;
		}		
		ps.setString(1, tsPoint.tsid);
		ps.setTimestamp(2, new Timestamp(tsPoint.time_stamp));
		ps.setDouble(3, tsPoint.x);
		ps.setDouble(4, tsPoint.y);
		ps.addBatch();
		index++;
		logger.info("add a point: " + tsPoint);
		if (index % bufferSize == 0) {
			ps.executeBatch();
			index = 0;
			logger.info("flush");
		}
	}
	

	
	
	/**
	 * Flash device info to database 
	 * @throws SQLException
	 */
	public void flashBatch()throws SQLException  {		
		if (ps != null && index > 1) {
			ps.executeBatch();	
			index = 0;
		}				
		
	}	

	/**
	 * Close batch.
	 */
	public void closeBatch() {
		try {			
			flashBatch();
		} catch (SQLException e) {
		}
		try {
			if (ps != null) {
				ps.close();
			}
		} catch (SQLException e) {			
		}
		ps = null;
	}

	public void reset(Connection conn) throws SQLException {
		this.conn = conn;
		this.ps = this.conn.prepareStatement(sqlString);
		this.index = 0;
	}
}
